package zuoye3;


import java.util.Scanner;

/**
 * 编程获取两个指定字符串中的最大相同子串。
 *
 *  如： s1="asdafghjka", s2="aaasdfg" 他们的最大子串为"asd"
 *  s1.contains(s2.subString(j,k))
 *  双层循环，一个控制头，一个控制尾
 *  提示： 将短的那个串进行长度依次递减的子串与较长的串比较。
 */
public class MaximumSameSubstring {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入任意长度字符串str1");
        String str1 = sc.nextLine();
        System.out.println(str1);
        System.out.println("请输入任意长度字符串str2");
        String str2 = sc.nextLine();
        System.out.println(str2);
        MaximumSameSubstring maximumSameSubstring = new MaximumSameSubstring();
        String s = maximumSameSubstring.MaximumTheSameSubString(str1, str2);
        System.out.println("最大相同子串为：" + s);
    }
    public String MaximumTheSameSubString(String a, String b) {
        String longstr;
        String shortstr;
        String sb1 = "";
        if (a.length() > b.length())
        {
            longstr = a;
            shortstr = b;
        }
        else
        {
            longstr = b;
            shortstr = a;
        }
        for (int i = 0;i<shortstr.length();i++) {
            for (int j=shortstr.length();j>i;j--) {
                if (longstr.contains(shortstr.substring(i,j))){
                    String sb2 = shortstr.substring(i,j);
                    if (sb2.length()> sb1.length()) {
                        sb1 = sb2;
                    }
                }
            }
        }
        return sb1;
    }
}
